package com.music.ui.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.download.DownloadInfo;
import com.lzy.okserver.download.DownloadManager;
import com.lzy.okserver.download.DownloadService;
import com.lzy.okserver.listener.DownloadListener;
import com.music.R;
import com.music.application.Constants;
import com.music.entity.online.OnlineMusicInfo;
import com.music.entity.online.SearchMusic;
import com.music.entity.online.SongPlay;
import com.music.loader.Api;
import com.music.loader.DataRequest;
import com.music.utils.CacheUtil;
import com.music.utils.StringUtil;
import com.music.utils.ToastUtil;

import java.io.File;
import java.util.List;

/**
 * Created by dingfeng on 2016/9/30.
 */
public class SearchSongAdapter extends BaseListAdapter<SearchMusic.SearchSong> {

    public SearchSongAdapter(Context context, List<SearchMusic.SearchSong> list) {
        super(context, list);
    }

    @Override
    public View bindView(final int position, View convertView, ViewGroup parent) {
        SearchMusic.SearchSong item = mList.get(position);
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.item_search_song, null);
            holder = new ViewHolder();
            holder.txtName = (TextView) convertView.findViewById(R.id.txtName);
            holder.txtArtist = (TextView) convertView.findViewById(R.id.txtArtist);
            holder.rlMore = (RelativeLayout) convertView.findViewById(R.id.rlMore);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.txtName.setText(item.getSongName());
        holder.txtArtist.setText(item.getArtistName());
        holder.rlMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onMoreClick(position);
            }
        });
        return convertView;
    }

    class ViewHolder {
        TextView txtName;
        TextView txtArtist;
        RelativeLayout rlMore;
    }

    private void onMoreClick(int position) {
        final SearchMusic.SearchSong song = mList.get(position);
        AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
        dialog.setTitle(song.getSongName());
        dialog.setItems(R.array.search_music_dialog, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:// 分享
                        share(song);
                        break;
                    case 1:// 下载
                        download(song);
                        break;
                }
            }
        });
        dialog.show();
    }


    private void share(final SearchMusic.SearchSong song) {
        DataRequest.getInstance().getOnlineUri(Api.METHOD_DOWNLOAD_MUSIC, song.getSongId(), new DataRequest.Callback<SongPlay>() {
            @Override
            public void onSuccess(SongPlay data) {
                String fileLink = "";
                if (data != null && data.getBitrate() != null) {
                    fileLink = data.getBitrate().getFilelink();
                }
                if (!StringUtil.isEmpty(fileLink)) {
                    Intent intent = new Intent(Intent.ACTION_SEND);
                    intent.setType("text/plain");
                    intent.putExtra(Intent.EXTRA_TEXT, data.getBitrate().getFilelink());
                    mContext.startActivity(Intent.createChooser(intent, mContext.getString(R.string.share)));
                } else {
                    Toast.makeText(mContext, R.string.file_link_error, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(String err) {
                Toast.makeText(mContext, R.string.file_link_error, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void download(final SearchMusic.SearchSong song) {
        DataRequest.getInstance().getOnlineUri(Api.METHOD_DOWNLOAD_MUSIC, song.getSongId(), new DataRequest.Callback<SongPlay>() {
            @Override
            public void onSuccess(SongPlay data) {
                String fileLink = "";
                if (data != null && data.getBitrate() != null) {
                    fileLink = data.getBitrate().getFilelink();
                }
                if (!StringUtil.isEmpty(fileLink)) {
                    download(song, fileLink);
                } else {
                    ToastUtil.showToast(R.string.download_link_error);
                }
            }

            @Override
            public void onError(String err) {
                Toast.makeText(mContext, err, Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void download(final SearchMusic.SearchSong song, String url) {
        DownloadManager downloadManager = DownloadService.getDownloadManager();
        downloadManager.setTargetFolder(Constants.DOWNLOAD);
        String fileName = song.getSongName() + Constants.SUFFIX_MP3;
        if (new File(Constants.DOWNLOAD + fileName).exists()) {
            ToastUtil.showToast(R.string.downloaded_tips);
        } else if (downloadManager.getDownloadInfo(url) != null) {
            ToastUtil.showToast(R.string.download_task_exist);
        } else {
            GetRequest request = OkGo.get(url);
            OnlineMusicInfo onlineMusicInfo = new OnlineMusicInfo();
            onlineMusicInfo.setTitle(song.getSongName());
            onlineMusicInfo.setArtistName(song.getArtistName());
            CacheUtil.getInstance(mContext).put(url, onlineMusicInfo);
            downloadManager.addTask(fileName, url, request, new DownloadListener() {

                @Override
                public void onAdd(DownloadInfo downloadInfo) {
                    super.onAdd(downloadInfo);
                    ToastUtil.showToast(mContext.getString(R.string.add_download_task, song.getSongName()));
                }

                @Override
                public void onProgress(DownloadInfo downloadInfo) {
                }

                @Override
                public void onFinish(DownloadInfo downloadInfo) {
                }

                @Override
                public void onError(DownloadInfo downloadInfo, String errorMsg, Exception e) {
                    ToastUtil.showToast(R.string.download_error);
                }

            });
        }
    }
}
